import re
from datetime import datetime

from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/newslist')
def get_news_list():
    cid = request.args.get("cid",1)
    page = request.args.get("page",1)
    per_page = request.args.get("per_page","10")

    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page )
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    filters = [News.status == 0]

    if cid != 1:
        filters.append(News.category_id == cid)

    print(*filters)
    try:

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    items = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    print(items)
    news_list = []

    for new in items:
        news_list.append(new.to_basic_dict())

    data = {
        "news_list":news_list,
        "total_page":total_page,
        "current_page":current_page
    }

    return jsonify(errno=RET.OK,errmsg='ok',data=data)


@index_blu.route('/')
@user_login_data
def index():

    news_list = None
    try:
        # 根据点击量 取出前6个
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='数据库错误')

    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new.to_basic_dict())

    category_list = None

    try:
        # 获取新闻分类
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    category_dict_li = []

    for category in category_list:
        category_dict_li.append(category.to_dict())


    user = g.user


    data = {
        "user":user.to_dict() if user else None,
        "news":news_dict_li,
        "category_list":category_dict_li
    }


    return render_template('news/index.html',data=data)

@index_blu.route('/favicon.ico')
def favicon():

    return current_app.send_static_file('news/favicon.ico')